package com.almond.admin.queue;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class ProductRequestMerger {
    private LinkedBlockingQueue<ProductRequest> queue = new LinkedBlockingQueue<>();
    private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

    public ProductRequestMerger() {
        // 启动定时任务，每隔10毫秒处理一次队列中的请求
        scheduledExecutorService.scheduleAtFixedRate(this::processBatch, 0, 10000, TimeUnit.MILLISECONDS);
    }

    public CompletableFuture<ProductInfo> getProductInfo(String productId) {
        CompletableFuture<ProductInfo> future = new CompletableFuture<>();
        ProductRequest request = new ProductRequest(productId, future);
        queue.offer(request);
        return future;
    }


    public CompletableFuture<ProductInfo> addProductInfo(String productId) {
        CompletableFuture<ProductInfo> future = new CompletableFuture<>();
        ProductRequest request = new ProductRequest(productId, future);
        queue.add(request);
        return future;
    }

    private void processBatch() {
        List<ProductRequest> requests = new ArrayList<>();
        queue.drainTo(requests);
        if (requests.isEmpty()) {
            return;
        }
        List<String> productIds = requests.stream().map(ProductRequest::getProductId).collect(Collectors.toList());
        List<ProductInfo> productInfos = batchQueryProductInfo(productIds);
        for (int i = 0; i < requests.size(); i++) {
            ProductRequest request = requests.get(i);
            ProductInfo productInfo = productInfos.get(i);
            request.getFuture().complete(productInfo);
            //TODO 处理业务
        }
    }

    private List<ProductInfo> batchQueryProductInfo(List<String> productIds) {
        // 模拟批量查询数据库
        List<ProductInfo> productInfos = new ArrayList<>();
        //查询数据库
        return productInfos;
    }
}